<template>
	<div class="filter">
		<template v-for="(item, index) in conditonList">
			<conditonItem
				:key="index"
				:fieldsList="fieldsList"
				:canDelete="canDelete"
				:conditonFilter="conditonFilter"
				@deleteItem="deleteItem(index)"
				@change="change"
				:conditonAnd="item"
			>
			</conditonItem>
			<el-divider
				:key="index + 'd'"
				class="divider"
			>或</el-divider>
		</template>
		<el-button
			icon="el-icon-plus iconfont-left"
			type="text"
			:class="conditonList.length ? 'margin-l' : ''"
			class="button-text"
			@click.stop="handleCommandOr"
			size="small"
		>添加条件</el-button>
	</div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Provide } from 'vue-property-decorator';
// eslint-disable-next-line no-restricted-imports
import { flatten } from 'lodash';
import conditonItem from './conditionItem.vue';
import { getOption } from './common';
@Component({
  name: 'condition',
  components: {
    conditonItem
  }
})
export default class extends Vue {
  @Prop(Array) public fieldsList!: any;
  @Prop(Array) public conditonList!: any;
  @Prop({ default: 'config' }) public type!: string;
  @Prop(String) public currentBusinessId!: string;
  @Prop({ default: () => [] }) public excludeConfig!: string[];
  private exclude = ['richText', 'remark', 'cuttingLine', 'externalComponent'].concat(this.excludeConfig);
  private get canDelete () {
    return flatten(this.conditonList).length > 1;
  }

  // 排除掉不需要展示的字段
  private get conditonFilter () {
    return this.fieldsList.filter((item) => {
      if (item.businessId === this.currentBusinessId) {
        return false;
      }
      if (this.exclude.includes(item.fieldType)) {
        return false;
      }
      if (item.fieldType === 'associationField') {
        return item.sourceField && !this.exclude.includes(item.sourceField.fieldType);
      }
      return true;
    });
  }

  // 添加条件
  public handleCommandOr () {
    const opt = getOption();
    // bugfix: el-dropdown关闭时，导致外面的条件筛选popover错误关闭
    setTimeout(() => {
      this.conditonList.push([opt]);
      this.change();
    });
  }

  public change () {
    this.$nextTick(() => {
      this.$emit('resetPosition');
    });
  }

  public deleteItem (index) {
    this.conditonList.splice(index, 1);
  }
}
</script>

<style lang="stylus" scoped>
.filter {
  // padding 8px 16px
}
.margin-l {
  margin-left 36px
}
</style>
